package com.components.update.util

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context.NOTIFICATION_SERVICE
import android.graphics.BitmapFactory
import android.os.Build
import androidx.core.app.NotificationCompat
import com.blankj.utilcode.util.ActivityUtils
import com.components.update.R

/**消息通知（用户显示下载进度）*/
object NotificationForProgressUtils {

    private val mProgressChannelId = "进度条渠道id"
    private val mProgressChannelName = "进度条通知"
    private lateinit var mManager: NotificationManager
    private lateinit var mBuilder: NotificationCompat.Builder
    private const val mProgressNotificationId = 9004 // 通知id

    fun createNotificationForProgressUtils(progressCurrent: Int, progressMax: Int) {
        mManager = ActivityUtils.getTopActivity()
            .getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                mProgressChannelId,
                mProgressChannelName,
                NotificationManager.IMPORTANCE_DEFAULT
            )
            mManager.createNotificationChannel(channel)
        }
        mBuilder = NotificationCompat.Builder(ActivityUtils.getTopActivity(), mProgressChannelId)
            .setContentTitle("更新进度")
            .setSmallIcon(R.drawable.icon_app_logo)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    ActivityUtils.getTopActivity().resources,
                    R.drawable.icon_app_logo
                )
            )
            // 第3个参数indeterminate，false表示确定的进度，比如100，true表示不确定的进度，会一直显示进度动画，直到更新状态下载完成，或删除通知
            .setProgress(progressMax, progressCurrent, false)
            .setAutoCancel(true)// 是否自动消失（点击）or mManager.cancel(mNormalNotificationId)、cancelAll、setTimeoutAfter()
        if (progressCurrent != 100) {
            mBuilder.setContentText("已完成:$progressCurrent%")
        } else {
            mBuilder.setContentText("下载完成")
            mManager.cancel(mProgressNotificationId)//下载完成后自动隐藏通知消息
        }
        mManager.notify(mProgressNotificationId, mBuilder.build())
    }

}